package jsontest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.util.Optional;
import java.util.function.Function;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class JSONEscapeTest {

    public static void main(String[] args) throws Exception {
        org.apache.commons.lang3.StringEscapeUtils d;
        String userinfo = "{\"appId\":\"\",\"userId\":\"\",\"userName\":\"\",\"userLevel\":\"" + 5 + "\"}";
        System.out.println(StringEscapeUtils.escapeJson(userinfo));
        System.out.println(userinfo);

        Function<InputStream, String> resourceReaderFunction = (InputStream jsonStris) -> {
            try (InputStream in = new FileInputStream("")) {
                return IOUtils.toString(in, "UTF-8");
            } catch (IOException e) {
            }
            return null;
        };

        Resource jsonResource = new ClassPathResource("/application.properties");

        System.out.println(resourceReaderFunction.apply(jsonResource.getInputStream()));

        doEnc();
    }

    public static void doEnc() throws Exception {
        // 生成key
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128);  // 确定密钥长度

        System.out.println(new String(kg.generateKey().getEncoded()));
        //byte[] keyBytes = kg.generateKey().getEncoded();
        byte[] keyBytes = "ABCDEFGHIJKLMNOP".getBytes();
// 格式化key
        Key key = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 确定算法
        cipher.init(Cipher.ENCRYPT_MODE, key);    // 确定密钥
        byte[] result = cipher.doFinal("{\"name\":\"中文\"}".getBytes());  // 加密
        String afterStr = Base64.encodeBase64String(result);
        System.out.println("加密后:" + afterStr);  // 不进行Base64编码的话，那么这个字节数组对应的字符串就是乱码

        cipher.init(Cipher.DECRYPT_MODE, key); // 进入解密模式
        // System.out.println(new String(cipher.doFinal(result))); // 解密

        System.out.println("解密--->" + new String(cipher.doFinal(Base64.decodeBase64(afterStr)))); // 解密
    }
}
